
/*
 * @项目名称: 模板开发
 * @FilePath: /meek/src/components/utils/imageadjust.js
 * @Author: kongxueyang@datatang.com
 * @Date: 2021-02-03T19:03:50+08:00
 * @LastEditors: kongxueyang@datatang.com
 * @LastEditTime: 2021-02-03T19:03:50+08:00
 * Copyright (c) 2018-2022
 */


export default class ImageAdjust {

  constructor(canvas, opts = {}) {

		var width = canvas.width;
    var height = canvas.height;
    var context = canvas.getContext('2d');
		var imgData = context.getImageData(0, 0, width, height);
		var offset = 0;
		var bri = Math.max(-255, Math.min(255, opts.brightness || 0));
		var con = Math.max(-255, Math.min(255, opts.contrast || 0));
		var rgb = {};

		if (con) con = Math.pow((con + 255) / 255, 2);

		for (var y = 0; y < height; y++) {
			// foreach row
			for (var x = 0; x < width; x++) {
				// for each pixel, skip if totally transparent
				if (imgData.data[ offset + 3 ] > 0) {
					rgb.r = imgData.data[ offset + 0 ];
					rgb.g = imgData.data[ offset + 1 ];
					rgb.b = imgData.data[ offset + 2 ];

					if (bri) {
						// apply brightness
						rgb.r = Math.max(0, Math.min(255, rgb.r + bri));
						rgb.g = Math.max(0, Math.min(255, rgb.g + bri));
						rgb.b = Math.max(0, Math.min(255, rgb.b + bri));
					}
					if (opts.contrast) {
						// apply contrast
						rgb.r = Math.floor( ((rgb.r / 255 - 0.5) * con + 0.5) * 255 );
						rgb.g = Math.floor( ((rgb.g / 255 - 0.5) * con + 0.5) * 255 );
						rgb.b = Math.floor( ((rgb.b / 255 - 0.5) * con + 0.5) * 255 );
					}

					imgData.data[ offset + 0 ] = rgb.r;
					imgData.data[ offset + 1 ] = rgb.g;
					imgData.data[ offset + 2 ] = rgb.b;
				}
				offset += 4;
			} // x loop
		} // y loop

		context.putImageData( imgData, 0, 0);
  }
}



